/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.gzx.plugin.ams.modular.purchase.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzx.plugin.ams.modular.commodity.service.AmsCommodityInfoService;
import com.gzx.plugin.ams.modular.purchase.entity.AmsPurchaseOrder;
import com.gzx.plugin.ams.modular.purchase.mapper.AmsPurchaseOrderMapper;
import com.gzx.plugin.ams.modular.purchase.param.AmsPurchaseOrderAddParam;
import com.gzx.plugin.ams.modular.purchase.param.AmsPurchaseOrderEditParam;
import com.gzx.plugin.ams.modular.purchase.param.AmsPurchaseOrderIdParam;
import com.gzx.plugin.ams.modular.purchase.param.AmsPurchaseOrderPageParam;
import com.gzx.plugin.ams.modular.purchase.service.AmsPurchaseOrderService;
import com.gzx.plugin.ams.modular.supplier.service.CommoditySupplierService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;

import java.math.BigDecimal;
import java.util.List;

/**
 * ams_purchase_orderService接口实现类
 *
 * @author 刘志刚
 * @date  2024/12/31 10:28
 **/
@Service
@RequiredArgsConstructor
public class AmsPurchaseOrderServiceImpl extends ServiceImpl<AmsPurchaseOrderMapper, AmsPurchaseOrder> implements AmsPurchaseOrderService {

    private final CommoditySupplierService commoditySupplierService;

    private final AmsCommodityInfoService amsCommodityInfoService;

    @Override
    @DS("ams")
    public Page<AmsPurchaseOrder> page(AmsPurchaseOrderPageParam amsPurchaseOrderPageParam) {
        QueryWrapper<AmsPurchaseOrder> queryWrapper = new QueryWrapper<AmsPurchaseOrder>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(amsPurchaseOrderPageParam.getMonth())) {
            queryWrapper.lambda().eq(AmsPurchaseOrder::getMonth, amsPurchaseOrderPageParam.getMonth());
        }
        if(ObjectUtil.isNotEmpty(amsPurchaseOrderPageParam.getType())){
            String typeStr = amsPurchaseOrderPageParam.getType();
            Integer type = Integer.parseInt(typeStr);
            queryWrapper.lambda().eq(AmsPurchaseOrder::getType, type);
        }
        if (ObjectUtil.isNotEmpty(amsPurchaseOrderPageParam.getDept())){
            queryWrapper.lambda().eq(AmsPurchaseOrder::getNeededDepartment, amsPurchaseOrderPageParam.getDept());
        }

        if(ObjectUtil.isNotEmpty(amsPurchaseOrderPageParam.getStart())){
            queryWrapper.lambda().ge(AmsPurchaseOrder::getMonth, amsPurchaseOrderPageParam.getStart().substring(0,7));
            queryWrapper.lambda().le(AmsPurchaseOrder::getMonth, amsPurchaseOrderPageParam.getEnd().substring(0,7));
        }
        if(ObjectUtil.isNotEmpty(amsPurchaseOrderPageParam.getProjectCode())){
            queryWrapper.lambda().eq(AmsPurchaseOrder::getProjectCode, amsPurchaseOrderPageParam.getProjectCode());
        }
        if(ObjectUtil.isNotEmpty(amsPurchaseOrderPageParam.getOfficeSupplies())) {
            queryWrapper.lambda().eq(AmsPurchaseOrder::getOfficeSupplies, amsPurchaseOrderPageParam.getOfficeSupplies());
        }
        if(ObjectUtil.isAllNotEmpty(amsPurchaseOrderPageParam.getSortField(), amsPurchaseOrderPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(amsPurchaseOrderPageParam.getSortOrder());
            queryWrapper.orderBy(true, amsPurchaseOrderPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(amsPurchaseOrderPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(AmsPurchaseOrder::getId);
        }
        if(ObjectUtil.isNotEmpty(amsPurchaseOrderPageParam.getCommodityName())){
            queryWrapper.lambda().eq(AmsPurchaseOrder::getCommodityCode, amsPurchaseOrderPageParam.getCommodityName());
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    @DS("ams")
    public void add(AmsPurchaseOrderAddParam amsPurchaseOrderAddParam) {
        amsPurchaseOrderAddParam.setCommodityName(amsCommodityInfoService.getCommdityByCode(amsPurchaseOrderAddParam.getCommodityCode()));
        AmsPurchaseOrder amsPurchaseOrder = BeanUtil.toBean(amsPurchaseOrderAddParam, AmsPurchaseOrder.class);
        amsPurchaseOrder.setMonth(amsPurchaseOrderAddParam.getMonth().substring(0,7));
        amsPurchaseOrder.setSupplierName(commoditySupplierService.getNameById(amsPurchaseOrderAddParam.getSupplierId()));
        this.save(amsPurchaseOrder);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    @DS("ams")
    public void edit(AmsPurchaseOrderEditParam amsPurchaseOrderEditParam) {
        amsPurchaseOrderEditParam.setCommodityName(amsCommodityInfoService.getCommdityByCode(amsPurchaseOrderEditParam.getCommodityCode()));
        AmsPurchaseOrder amsPurchaseOrder = this.queryEntity(amsPurchaseOrderEditParam.getId().toString());
        if(ObjectUtil.isNotEmpty(amsPurchaseOrderEditParam.getSupplierCode())){
            amsPurchaseOrder.setSupplierName(commoditySupplierService.getNameById(amsPurchaseOrderEditParam.getSupplierCode()));
        }
        BeanUtil.copyProperties(amsPurchaseOrderEditParam, amsPurchaseOrder);
        this.updateById(amsPurchaseOrder);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    @DS("ams")
    public void delete(List<AmsPurchaseOrderIdParam> amsPurchaseOrderIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(amsPurchaseOrderIdParamList, AmsPurchaseOrderIdParam::getId));
    }

    @Override
    @DS("ams")
    public AmsPurchaseOrder detail(AmsPurchaseOrderIdParam amsPurchaseOrderIdParam) {
        return this.queryEntity(amsPurchaseOrderIdParam.getId().toString());
    }

    @Override
    @DS("ams")
    public AmsPurchaseOrder queryEntity(String id) {
        AmsPurchaseOrder amsPurchaseOrder = this.getById(id);
        if(ObjectUtil.isEmpty(amsPurchaseOrder)) {
            throw new CommonException("ams_purchase_order不存在，id值为：{}", id);
        }
        return amsPurchaseOrder;
    }

    /**
     * 获取采购总金额
     * @param amsPurchaseOrderPageParam
     * @return
     */
    @Override
    @DS("ams")
    public String getMoney(AmsPurchaseOrderPageParam amsPurchaseOrderPageParam) {
        QueryWrapper<AmsPurchaseOrder> queryWrapper = new QueryWrapper<AmsPurchaseOrder>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(amsPurchaseOrderPageParam.getMonth())) {
            queryWrapper.lambda().eq(AmsPurchaseOrder::getMonth, amsPurchaseOrderPageParam.getMonth());
        }
        if(ObjectUtil.isNotEmpty(amsPurchaseOrderPageParam.getType())){
            String typeStr = amsPurchaseOrderPageParam.getType();
            Integer type = Integer.parseInt(typeStr);
            queryWrapper.lambda().eq(AmsPurchaseOrder::getType, type);
        }
        if (ObjectUtil.isNotEmpty(amsPurchaseOrderPageParam.getDept())){
            queryWrapper.lambda().eq(AmsPurchaseOrder::getNeededDepartment, amsPurchaseOrderPageParam.getDept());
        }

        if(ObjectUtil.isNotEmpty(amsPurchaseOrderPageParam.getStart())){
            queryWrapper.lambda().ge(AmsPurchaseOrder::getMonth, amsPurchaseOrderPageParam.getStart().substring(0,7));
            queryWrapper.lambda().le(AmsPurchaseOrder::getMonth, amsPurchaseOrderPageParam.getEnd().substring(0,7));
        }
        if(ObjectUtil.isNotEmpty(amsPurchaseOrderPageParam.getProjectCode())){
            queryWrapper.lambda().eq(AmsPurchaseOrder::getProjectCode, amsPurchaseOrderPageParam.getProjectCode());
        }
        if(ObjectUtil.isNotEmpty(amsPurchaseOrderPageParam.getOfficeSupplies())) {
            queryWrapper.lambda().eq(AmsPurchaseOrder::getOfficeSupplies, amsPurchaseOrderPageParam.getOfficeSupplies());
        }
        if(ObjectUtil.isAllNotEmpty(amsPurchaseOrderPageParam.getSortField(), amsPurchaseOrderPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(amsPurchaseOrderPageParam.getSortOrder());
            queryWrapper.orderBy(true, amsPurchaseOrderPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(amsPurchaseOrderPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(AmsPurchaseOrder::getId);
        }
        if(ObjectUtil.isNotEmpty(amsPurchaseOrderPageParam.getCommodityName())){
            queryWrapper.lambda().eq(AmsPurchaseOrder::getCommodityCode, amsPurchaseOrderPageParam.getCommodityName());
        }
        List<AmsPurchaseOrder> list = this.list(queryWrapper);
        BigDecimal bigDecimal = new BigDecimal("0");

        for (AmsPurchaseOrder amsPurchaseOrder : list) {
            bigDecimal = bigDecimal.add(amsPurchaseOrder.getTotalPrice());
        }
        return bigDecimal+"元";
    }
}
